<?php
class AccountModel extends CommonModel
{
	public function __construct($uid)
	{
		parent::__construct('account');
	    if(empty($uid) || intval($uid) != $uid){trigger_error("UID ERROR!");exit;}
	    $this->uid = $uid;
	}
	
	protected function _setFields()
	{
		return array(
			'AID',
		    'UID',
			'AccountName',
			'AccountType',
			'Bank',
			'Status',
			'CreateDate',
			'Remark'
		);
	}
	
	protected function _setPrimaryKeys()
	{
		return array(
			'AID'
		);
	}
	
	protected function _setAutoIncrementFields()
	{
		return array(
			'AID'
		);
	}
	
	protected function _setForeignKeyRelation()
	{
		return array();
	}
	
	public function add($data)
	{
		$initAssets = floatval($data['InitAssets']);
		$data = $this->_getFieldsData($data);
		$dbMaster = DB::getMaster();
		$sql = "INSERT INTO `{$this->_table}`(`UID`,`AccountName`,`AccountType`,`Bank`,`TotalAssets`,`Status`,`CreateDate`,`Remark`) 
				VALUES('{$data['UID']}','{$data['AccountName']}', '{$data['AccountType']}', '{$data['Bank']}','{$initAssets}','{$data['Status']}', '{$data['CreateDate']}', '{$data['Remark']}')";
		
		$dbMaster->beginTransaction();
		$res = $dbMaster->exec($sql);
		if($dbMaster->isError())
		{
			$dbMaster->rollBack();
			return false;
		}
		
		if($initAssets > 0)
		{
			$accountID = $dbMaster->lastInsertId();
			$tpre = Config::getConfig('DB_TABLE_PRE');
			$diaryDate = time();
			$sql = "INSERT INTO `{$tpre}record`(`UID`, `AccountID`,`Income`,`Expend`,`DiaryDate`,`Remark`) 
					VALUES('{$this->uid}', '{$accountID}','{$initAssets}','0.00','{$diaryDate}','账户初始金额')";
			$res = $dbMaster->exec($sql);
			if($dbMaster->isError())
			{
				$dbMaster->rollBack();
				return false;
			}
		}
		$dbMaster->commit();
		return true;
	}
	
	public function edit($data)
	{
	    $data = $this->_getFieldsData($data, true);
		$dbMaster = DB::getMaster();
		$setStr = $this->_getUpdateFiledStr($data);
		$sql = "UPDATE `{$this->_table}` SET 
				{$setStr}
				WHERE AID='{$data['AID']}' AND UID='{$this->uid}'";
		$dbMaster->exec($sql);
		return !$dbMaster->isError();
	}
	
	public function adj($accountID, $newTotalAssets, $oldTotalAssets, $adjNote = '余额调整')
	{
		$newTotalAssets = (float)$newTotalAssets;
		$recordValue = $newTotalAssets - (float)$oldTotalAssets;
		$recordCls = new RecordModel($this->uid);
		$data = array();
		$data['AccountID'] = $accountID;
		
		if($recordValue > 0 )
		{
			$data['Expend'] = 0;
			$data['Income'] = $recordValue;
		}
		else 
		{
			$data['Expend'] = abs($recordValue);
			$data['Income'] = 0;
		}
		$data['DiaryDate'] = time();
		$data['Remark'] = $adjNote;
		
		return $recordCls->add($data);
	}
	
	public function cancel($AID)
	{
		$sql = "UPDATE `{$this->_table}` SET 
				`Status`='0'
				WHERE AID='{$AID}' AND UID='{$this->uid}'";
		$dbMaster = DB::getMaster();
		$dbMaster->exec($sql);
		if($dbMaster->isError())
		{
			return false;
		}
		$account = $this->getAccountByID($AID);
		if(empty($account)) return false;
		
		$recordCls = new RecordModel($this->uid);
		$data = array();
		$data['AccountID'] = $AID;
		$data['Income'] = '0';
		$data['Expend'] = $account['TotalAssets'];
		$data['DiaryDate'] = time();
		$data['Remark'] = '账户注销，余额清零';
		if(!$recordCls->add($data))
		{
			$this->restore($AID);
			return false;
		}
		return true;
	}
	
	public function restore($AID)
	{
		$sql = "UPDATE `{$this->_table}` SET 
				`Status`='1'
				WHERE AID='{$AID}' AND UID='{$this->uid}'";
		$dbMaster = DB::getMaster();
		$dbMaster->exec($sql);
		return !$dbMaster->isError();
	}
	
	public function getAccountByID($AID)
	{
	    $AID = intval($AID);
	    if(empty($AID)) return array();
	    $dbSlave = DB::getSlave();
	    $sql = "SELECT * FROM `{$this->_table}` WHERE `AID`='{$AID}' AND `UID`='{$this->uid}'";
	    return $dbSlave->getRow($sql);
	}
	
	/**
	 * 获取账户列表
	 * @param int $type 获取类型，0:注销的，1：启用的，2：全部
	 */
	public function getAccounts($type = 1)
	{
		$statusWhere = '';
		if($type == 0)
		{
			$statusWhere = 'a.Status = 0 AND ';
		}
		else if($type == 1)
		{
			$statusWhere = 'a.Status = 1 AND ';
		}
		$dbSlave = DB::getSlave();
		$tpre = Config::getConfig('DB_TABLE_PRE');
		$sql = "SELECT a.AID, a.AccountName, a.AccountType, s.AccountTypeName, 
				a.Status, org.OrganName AS BankName, a.TotalAssets, a.CreateDate, a.Remark
				FROM `{$this->_table}` AS a 
				LEFT JOIN `{$tpre}account_type` AS s ON a.AccountType=s.AID
				LEFT JOIN `{$tpre}organ` AS org ON a.Bank=org.AID AND org.OrganType=1 AND org.UID='{$this->uid}'
				WHERE {$statusWhere}a.UID='{$this->uid}'
				GROUP BY a.AID, a.AccountName, a.AccountType, a.Status, s.AccountTypeName, a.Remark, a.TotalAssets
				ORDER BY s.AID DESC, a.AID DESC, org.AID DESC";
		return $dbSlave->query($sql);
	}
	
	public function getTotal()
	{
		$dbSlave = DB::getSlave();
		$sql = "SELECT SUM(TotalAssets) AS TotalAssets
				FROM `{$this->_table}`
				WHERE Status = 1 AND UID='{$this->uid}'";
		$result = $dbSlave->getRow($sql);
		$total = !empty($result) ? $result['TotalAssets'] : 0;
		return $total;
	}

	protected function _validationField($fieldName, $value) 
	{
		return true;
	}
	
	public function __destruct()
	{
		//echo 'account model destruct!';
	}
}